package gwtappcontainer.server.apis.home;

import static com.googlecode.objectify.ObjectifyService.ofy;
import gwtappcontainer.server.DatastoreNamespaces;

import java.util.List;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.ObjectifyService;

class HomeRepository {
	
	static {		
		ObjectifyService.factory().register(AllAppURLEntity.class);				
	}

	private final String NAMESPACE = DatastoreNamespaces.HOME; 

	public String getAllIconsAndURLsAsHtml() {
		NamespaceManager.set(NAMESPACE);
		
		List<AllAppURLEntity> all = ofy().load().type(AllAppURLEntity.class).list();
		
		String html = "No apps found !";
		
		if (0 != all.size()) {
			html = all.get(0).allIconsAndURLsHtml;
		}
					
		return html;
	}
	
	public String setAllIconsAndURLsAsHtml(String html) {
		NamespaceManager.set(NAMESPACE);
								
		//delete all existing entities
		List<AllAppURLEntity> all = ofy().load().type(AllAppURLEntity.class).list();
		if (0 != all.size())
			ofy().delete().entities(all).now();
				
		//and create a new one
		AllAppURLEntity entity = new AllAppURLEntity();
		entity.allIconsAndURLsHtml = html;
		
		ofy().save().entity(entity).now();
		
		all = ofy().load().type(AllAppURLEntity.class).list();
			
		String ret = "";
		if (0 != all.size())
			ret = all.get(0).allIconsAndURLsHtml;
		
		return ret;
	}
}
